package DBLayer;

import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;

import DomainLayer.Bed;
import DomainLayer.Room;
import DomainLayer.Session;
import DomainLayer.Journal;

public class DBRoom  {

	private Connection con;

	public DBRoom() {
		con = DbConnection1.getInstance().getDBcon();
	}

	
	

	

	
	
	public Room findRoom(int room_No ) {
		String wClause = " room_No= " +room_No;
		return singleWhere(wClause);
	}

	private Room singleWhere(String wClause) {
		ResultSet results;
		Room roomObj = new Room();

		String query = buildQuery(wClause);
		System.out.println(query);
		try { // read the session from the database
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);

			if (results.next()) {
				roomObj = buildRoom(results);
				// association is to be build

				stmt.close();

			} else { // no Session was found
				roomObj = null;
			}
		}// end try
		catch (Exception e) {
			System.out.println("Query exception: " + e);
		}
		return roomObj;
	}

	private Room buildRoom(ResultSet results) {
		Room roomObj = new Room();
		try { // the columns from the table emplayee are used
			roomObj.setRoom_No(results.getInt(1));
		  ArrayList<Bed> beds = new ArrayList<Bed>();
		  for (int i=1;i<=results.getInt(2);i++){
				beds.add(new Bed(i,roomObj));
			}
		  
		  roomObj.setBeds(beds);
			
		} catch (Exception e) {
			System.out.println("error in building the customer object");
		}
		return roomObj;
	}

	private String buildQuery(String wClause) {
		String query = "SELECT room_No, number_of_beds From Room";

		if (wClause.length() > 0)
			query = query + " WHERE " + wClause;

		return query;
	}
	
	
	

	

	

	

	

}
